package com.mars.basic.security.config.security.service.impl;


import com.mars.basic.allmain.po.AdminUser;
import com.mars.basic.allmain.po.Role;
import com.mars.basic.security.config.security.dto.SecurityUser;
import com.mars.basic.service.AdminRoleService;
import com.mars.basic.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p> 自定义userDetailsService - 认证用户详情 </p>
 *
 * @author : zhengqing
 * @description :
 * @date : 2019/10/14 17:46
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private AdminUserService adminUserService;

  @Autowired
  private AdminRoleService adminRoleService;

    /***
     * 根据账号获取用户信息
     * @param username:
     * @return: org.springframework.security.core.userdetails.UserDetails
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        AdminUser adminUser = adminUserService.findByUserName(username);
        // 判断用户是否存在
        if (adminUser==null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        List<Role> list = adminRoleService.findRolesByAdminId(adminUser.getId());
        System.out.println(list);
        // 返回UserDetails实现类
        return new SecurityUser(adminUser, list);
    }

}
